package com.xhs.service;

import com.xhs.model.SearchTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 任务执行服务
 *
 * @author xhs
 */
@Slf4j
@Service
public class TaskExecutionService {

    @Autowired
    private TaskSchedulerService taskSchedulerService;

    @Autowired
    private TaskService taskService;

    /**
     * 立即执行任务
     *
     * @param taskId 任务ID
     */
    public void executeTaskImmediately(Long taskId) {
        SearchTask task = taskService.getTask(taskId);
        if (task == null) {
            log.warn("任务不存在，无法执行: taskId={}", taskId);
            return;
        }

        log.info("开始立即执行任务: taskId={}, taskName={}", taskId, task.getTaskName());
        
        // 使用异步方式执行任务，避免阻塞接口响应
        new Thread(() -> {
            try {
                taskSchedulerService.executeTaskImmediately(task);
            } catch (Exception e) {
                log.error("立即执行任务失败: taskId={}", taskId, e);
                taskService.updateTaskStatus(taskId, "FAILED");
            }
        }).start();
    }
} 